package com.geekgo.runningjava.multithread;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * ExecutorService 的shutdown 和 shutdownNow的区别
 * @author geekgo
 * @version 2016/12/27 14:17
 */
public class ShutdownAndShutdownNow {

    public static void main(String[] args){

        try {
            testShutdown(100);
            testShutdownNow(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void testShutdown(int startNo) throws InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for(int i = 0;i<5;i++){
            executorService.execute(getTask(startNo+i));
        }
        executorService.shutdown();
        final boolean done = executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("shutdown-->all threads shutdown:"+done);
    }
    public static void testShutdownNow(int startNo) throws InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(2);
        for(int i = 0;i<5;i++){
            executorService.execute(getTask(startNo+i));
        }
        final List<Runnable> rejected = executorService.shutdownNow();
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
        System.out.println("shutdownnow-->all threads shutdown，rejected threads has "+rejected.size()+"个。");
    }
    private static Runnable getTask(final int threadNo){
        Runnable task = new Runnable() {
            public void run() {
                System.out.println(threadNo+"-->"+(int)(Math.random()*10));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    System.out.println("Thread "+threadNo+"has error: "+e);
                }
            }
        };
        return task;
    }
}
